package com.community.demo.config;


import cn.hutool.core.collection.CollectionUtil;
import com.community.demo.dao.PermissionRepository;
import com.community.demo.dao.RoleRepository;
import com.community.demo.dao.UserRepository;
import com.community.demo.domain.Permission;
import com.community.demo.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CustomAccess {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    public Boolean a(HttpServletRequest req, Authentication auth){
        // 没有登录
        // 1.获取到当前用户
        Object principal = req.getUserPrincipal();
        if(principal == null || "anonymousUser".equals(principal)) {
            return false;
        }

        // 2.根据url查询Permission
        String url = req.getRequestURI();
        // 获取当前url的role集合
        List<Permission> permissionList = permissionRepository.findAllByUrl(url);

        // 白名单机制
        if(permissionList.size() < 1){
            // 说明针对此用户没有设置权限，直接通过
            return true;
        }

        // 3. 获取当前url对应的ROLE
//        List<Role> urlRoleList = new ArrayList<>();
//        permissionList.forEach(permission -> {
//            urlRoleList.addAll(permission.getRoles());
//        });
        List<String> urlRoleList = permissionList.stream()
                .flatMap(p -> p.getRoles().stream())
                .map(Role::getName)
                .collect(Collectors.toList());

        // 4.获取到当前用户拥有的角色
//        Collection<? extends GrantedAuthority> userRoleList = auth.getAuthorities();
        List<String> userRoleList = auth.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        // 5.urlRoleList 和 userRoleList 如果存在交集，说明用户有权限访问此url
//        for(Role role : urlRoleList){
//            for(GrantedAuthority authority : userRoleList){
//                if(role.getName().equals(authority.getAuthority())){
//                    return true;
//                }
//            }
//        }

        return !CollectionUtil.isEmpty(CollectionUtil.intersection(urlRoleList, urlRoleList));
    }
}
